package me.dwliu.springcloud.interceptor;

import com.alibaba.fastjson.JSON;
import me.dwliu.springcloud.util.UserContextHolder;
import me.dwliu.springcloud.util.UserPermissionUtil;
import me.dwliu.springcloud.vo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserContextInterceptor extends HandlerInterceptorAdapter {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserContextInterceptor.class);


    @Override

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ServletWebRequest servletWebRequest = new ServletWebRequest(request);
        User user = getUser(servletWebRequest);

        UserPermissionUtil.permission(user);

        if (!UserPermissionUtil.verify(user, servletWebRequest)) {
            response.setHeader("Content-Type", "application/json");
            String str = JSON.toJSONString("用户没有权限");
            response.getWriter().write(str);
            response.getWriter().flush();
            response.getWriter().close();
            throw new RuntimeException("用户没有权限");
        }

        UserContextHolder.set(user);
        return true;


    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LOGGER.debug("删除用户信息：{}", UserContextHolder.currentUser());
        UserContextHolder.revome();
    }


    private User getUser(ServletWebRequest request) {
        String userId = request.getHeader(User.USER_ID);
        String username = request.getHeader(User.USER_NAME);

        User user = new User(userId, username);
        return user;
    }

}
